import { Input, NavBar, TextArea } from 'antd-mobile'
import styles from './index.module.scss'
import { useState, useRef, useEffect } from 'react'
import { useInitState } from '@/utils/hooks'
import { getUserProfile } from '@/store/actions/profile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'

type Props = {
  hideInput: () => void,
  type: '' | 'name' | 'intro',
  onUpdate: (key: string, value: string) => void
}

const EditInput = ({ hideInput, type, onUpdate }: Props) => {
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)

  const { userProfile } = useInitState(getUserProfile, 'profile')
  const [value, setValue] = useState(
    type === 'name' ? userProfile.name : userProfile.intro
  )

  // 使用useEffect保证组件渲染的时候自动获取焦点
  useEffect(() => {
    if (type === 'name') {
      inputRef.current?.focus()
    } else {
      textRef.current?.focus()
      // 光标位置bug-处理
      document.querySelector('textarea')?.setSelectionRange(-1, -1)
    }
  }, [type])
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={
          <span
            className="commit-btn"
            onClick={() => onUpdate(type, value)}>
            提交
          </span>
        }
        onBack={hideInput}
      >
        编辑{type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{type === 'name' ? '昵称' : '简介'}</h3>

        {type === 'name' ?
          (<div className="input-wrap">
            <Input
              placeholder="请输入昵称"
              value={value}
              onChange={(e) => setValue(e)}
              ref={inputRef} />
          </div>)
          : <TextArea
            className="textarea"
            placeholder="请输入简介"
            showCount
            maxLength={99}
            value={value}
            onChange={(e) => setValue(e)}
            ref={textRef}
          />}
      </div>
    </div>
  )
}

export default EditInput
